package cn.itcast.web.shiro;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义realm域
 */
public class AuthRealm extends AuthorizingRealm {

 @Autowired
 private UserService userService;

 @Autowired
 private ModuleService moduleService;

 /**
  * 授权
  */
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  //获取当前登录用户（安全数据）
  User user = (User) principalCollection.getPrimaryPrincipal();
  // 根据当前登录用户，查询此用户的所有模块权限
  List<Module> list = moduleService.findByUser(user);
  //提取所有的模块名称
  Set<String> permissions = new HashSet<>();
  for (Module module : list) {
   permissions.add(module.getName());
  }
  //构造返回值
  SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  info.setStringPermissions(permissions);
  return info;
 }
 /**
  * 认证
  */
 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  //获取登录的用户名和密码
  UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
  String email = upToken.getUsername();
  String password = new String(upToken.getPassword());
  //调用service查询
  User user = userService.findByEmail(email);
  //判断用户是否存在
  if (user != null) {
   //用户存在，构造info返回值
   return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
  } else {
   //用户不存在，返回空自动抛出异常
   return null;
  }
 }
}
